﻿using System;
using AfterlifeLib.Levels;
using Microsoft.Xna.Framework;

namespace AfterlifeLib.Collision
{
    public static class CollisionHelper
    {
        public static bool IsColliding(CollisionLayer collisionLayer, Vector2 position, int width, int height)
        {
            int tileY = (int)Math.Floor(position.Y / Level.TileDrawHeight);
            int tileX = (int)Math.Floor(position.X / Level.TileDrawWidth);
            int tileYPH = (int)Math.Floor((position.Y + height - 1) / Level.TileDrawHeight);
            int tileXPW = (int)Math.Floor((position.X + width - 1) / Level.TileDrawWidth);

            return (
                collisionLayer[tileX, tileY] != 1 &&
                collisionLayer[tileXPW, tileY] != 1 &&
                collisionLayer[tileX, tileYPH] != 1 &&
                collisionLayer[tileXPW, tileYPH] != 1);
        }

        public static Vector2 GetNewPosition(CollisionLayer collisionLayer, Vector2 position, Vector2 velocity, int width, int height)
        {
            bool walkX = IsColliding(collisionLayer, new Vector2(position.X + velocity.X, position.Y), width, height);
            bool walkY = IsColliding(collisionLayer, new Vector2(position.X, position.Y + velocity.Y), width, height);

            return new Vector2(position.X + (walkX ? velocity.X : 0), position.Y + (walkY ? velocity.Y : 0));
        }

        /// <summary>
        /// Wether the position is in a Rectangle.
        /// </summary>
        /// <param name="position">The position to check.</param>
        /// <param name="rect">The Rectangle to check.</param>
        /// <returns>Wether we are in the rect.</returns>
        public static bool InRectangle(Vector2 position, Rectangle rect)
        {
            if (position.X > rect.Left &&
                position.X < rect.Right &&
                position.Y > rect.Top &&
                position.Y < rect.Bottom)
                return true;

            return false;
        }
    }
}
